package com.mokairui.example.demo;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
import java.util.Scanner;

/**
 * @author Mokairui
 * @Description 客户端案例实现-基于NIO非阻塞通信
 * @Since 2021/6/29
 */
public class Client {
    public static void main(String[] args) throws IOException {
        // 1.获取通道
        SocketChannel socketChannel = SocketChannel
                .open(new InetSocketAddress("127.0.0.1", 9999));
        // 2.切换非阻塞模式
        socketChannel.configureBlocking(false);
        // 3.分配缓冲区大小
        ByteBuffer buffer = ByteBuffer.allocate(1024);
        // 4.发送数据给服务器
        Scanner scanner = new Scanner(System.in);
        while (true) {
            System.out.println("请说：");
            String msg = scanner.nextLine();
            buffer.put((socketChannel.getRemoteAddress() + ":" + msg).getBytes());
            buffer.flip();
            socketChannel.write(buffer);
            buffer.clear();
        }
    }
}
